package config

import (
	"errors"
	"fmt"
	"gitee.com/vrv_media/go-micro-framework/pkg/common/util/fileutil"
	"github.com/spf13/viper"
)

// ReadFile 通用的读取配置文件的方法，传入路径和文件名以及类型，返回一个Viper的指针
func ReadFile(filePath, fileName, configType string) (config *viper.Viper, err error) {
	config = viper.New()
	filePath = fileutil.TransToRedirectPaths([]string{filePath})[0]
	config.AddConfigPath(filePath)
	config.SetConfigName(fileName)
	config.SetConfigType(configType)
	if err := config.ReadInConfig(); err != nil {
		var configFileNotFoundError viper.ConfigFileNotFoundError
		if errors.As(err, &configFileNotFoundError) {
			fmt.Println("Not found config file")
		}
	}
	return
}

// ReadIniConfig 读取ini类型配置文件
func ReadIniConfig(filePath, fileName string) (*viper.Viper, error) {
	return ReadFile(filePath, fileName, "ini")
}

// ReadJsonConfig 读取json类型配置文件
func ReadJsonConfig(filePath, fileName string) (*viper.Viper, error) {
	return ReadFile(filePath, fileName, "json")
}

// ReadYamlConfig 读取yaml类型配置文件
func ReadYamlConfig(filePath, fileName string) (*viper.Viper, error) {
	return ReadFile(filePath, fileName, "yaml")
}

func MappingConfigToStruct(config *viper.Viper, configTypes ...interface{}) error {
	if config == nil || len(configTypes) == 0 {
		return nil
	}
	for _, configType := range configTypes {
		err := config.Unmarshal(configType)
		if err != nil {
			return err
		}
	}
	return nil
}
